<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Play_model extends Teaboy_model{
	
		private $gameDuration = 30; //how long the hame should run for
	
		public function __contruct(){
			parent::Controller();
		}
		
		
		/*
		 * Creates a new instance of the game
		 */
		public function newGame(){
			
			//create game in DB
			$gameId = $this->createGame();
			
			//send notifications
			$this->Notify_model->sendPreWarning();
			
			$this->launchSequence();
			
			
		}
		
		public function endGame(){
			
			//send game over message
			$this->Notify_model->gameOver();
			sleep(1);
			//send result
			$this->Notify_model->sendResults();
 		
		}
		
		private function launchSequence($remaining = 10){
			
			//send start
			$this->Notify_model->sendCountdown($remaining);
			if($remaining == 60){
				$aAlerts = array(10, 10, 10 , 10, 10, 5, 1, 1, 1, 1); //60 second
			} else {
				$aAlerts = array(5, 1, 1, 1, 1); //10 second
			}
			foreach($aAlerts as $alert){
				$remaining = $remaining - $alert;
				sleep($alert);
				$this->Notify_model->sendCountdown($remaining);
			}
			
			//start game
			$this->Notify_model->gameStart();
			
			//wait for game to run
			sleep($this->gameDuration);
			$this->endGame();
			
		}
		
		private function createGame(){
			$sSQL = "INSERT INTO game (date_time) VALUES (now())";
			$this->db->query($sSQL);
			
			$id = $this->db->insert_id();
			if(is_int($id)){
				return $id;
			}
			
			return false;
		}

		public function shake($drinkerId, $gameId, $duration, $beverage){
			
			$beverage_id = 2;
			if(strtolower($beverage) == 'tea'){
				$beverage_id = 1;
			}
			
			$sSQL = "INSERT INTO shakes (game_id, drinker_id, duration, date_time, beverage_id) VALUES (?, ?, ?, now(), ?)";
			$this->db->query($sSQL, array($gameId, $drinkerId, $duration, $beverage_id));
			
			return true;
		}
		
		
}